﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace DarwinIsDead {
    class Finch : Entity {
        private const float DISTANCE = 600f;
        public Vector2 InitialPosition { get; set; }
        public Color Color { get; set; }
        public float Rise { get; set; }

        private float speed;
        public float Speed {
            get { return speed; }
            set { 
                speed = value;
                if (speed < 0f) {
                    flip = true;
                }
            }
        }

        private float time;
        private float distanceCount;

        private Texture2D sprite;
        private List<Rectangle> frames;
        private int frame;
        private float frameTime;
        private float frameCount;
        private bool flip;

        private bool enabled;

        public Finch(World world)
            : base(world, new Rectangle()) {
            Color = Color.White;
            Rise = 1f;
            Speed = 1f;

            time = 0f;

            sprite = world.Game.Content.Load<Texture2D>("Sprites\\sprFinch");
            frames = new List<Rectangle>();
            frames.Add(new Rectangle(0, 0, 15, 17));
            frames.Add(new Rectangle(15, 0, 15, 17));
            frame = 0;
            frameTime = 0.1f;
            frameCount = 0f;
            distanceCount = 0f;
        }

        public void Spawn(Vector2 position) {
            time = 0f;
            distanceCount = 0f;
            InitialPosition = position;
            enabled = true;
        }

        public override void Update(GameTime gameTime) {
            if (enabled) {
                float dt = (float)(gameTime.ElapsedGameTime.Milliseconds / 1000.0);
                time += dt;

                SetPosition(InitialPosition.X + time * Speed,
                            InitialPosition.Y - (time * time * Rise));

                frameCount += dt;
                if (frameCount > frameTime) {
                    frameCount = 0f;
                    frame = (frame + 1) % frames.Count;
                }

                distanceCount += Speed * dt;
                if (distanceCount > DISTANCE) {
                    enabled = false;
                }

                Depth = -(int)Position.Y;
            }
        }

        public override void Draw(SpriteBatch spriteBatch) {
            if (enabled) {
                spriteBatch.Draw(sprite, Position, frames[frame], Color, 0f, Vector2.Zero, 2f,
                    flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, 0f);
            }
        }
    }
}
